from __future__ import annotations

import textwrap
from datetime import datetime, timezone
from pathlib import Path
from subprocess import CalledProcessError, check_output
from typing import Any


def write_build_info(
    project_dir: str | Path, template_fields: dict[str, Any], params: dict[str, Any]
) -> None:
    """
    Write the build info to the project directory.
    """
    path = Path(project_dir) / params.get("path", "src/prefect/_version.py")

    try:
        git_hash = check_output(["git", "rev-parse", "HEAD"]).decode().strip()
    except CalledProcessError:
        git_hash = "unknown"

    build_dt_str = template_fields.get(
        "build_date", datetime.now(timezone.utc).isoformat()
    )
    version = template_fields.get("version", "unknown")
    dirty = "dirty" in version

    build_info = textwrap.dedent(
        f"""\
            # Generated by versioningit
            __version__ = "{version}"
            __build_date__ = "{build_dt_str}"
            __git_commit__ = "{git_hash}"
            __dirty__ = {dirty}
            """
    )

    with open(path, "w") as f:
        f.write(build_info)
